<template>
  <div id="main">
    <a-row id="row">
      <a-col class="col" span="8">
        <a-card>
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" title="题目">
              <a-card
                v-if="question"
                :style="{ width: '100%' }"
                :title="question.title"
              >
                <a-descriptions
                  title="判题条件"
                  :column="{ xs: 1, md: 2, lg: 3 }"
                >
                  <a-descriptions-item label="时间限制">
                    {{ question.judgeConfig.timeLimit ?? 0 }}
                  </a-descriptions-item>
                  <a-descriptions-item label="内存限制">
                    {{ question.judgeConfig.memoryLimit ?? 0 }}
                  </a-descriptions-item>
                  <a-descriptions-item label="堆栈限制">
                    {{ question.judgeConfig.stackLimit ?? 0 }}
                  </a-descriptions-item>
                </a-descriptions>

                <MdViewer :value="question.content" />
              </a-card>
            </a-tab-pane>
            <a-tab-pane key="2" title="讨论区"> 讨论区暂不可用</a-tab-pane>
            <a-tab-pane key="3" title="提交记录">
              <div>
                <a-list
                  @pageChange="onPageChange"
                  :pagination-props="paginationProps"
                  :data="judgeData"
                >
                  <template #item="{ item }">
                    <a-list-item
                      class="list-demo-item"
                      action-layout="vertical"
                    >
                      <a-card :title="item.lang" hoverable>
                        <template #extra>
                          <p
                            :style="{
                              color: '#e6ff70',
                            }"
                            v-if="item.state === 0"
                          >
                            判题中
                          </p>
                          <p
                            :style="{
                              color: '#57e537',
                            }"
                            v-if="
                              item.state === 1 &&
                              item.judgeInfo.message === 'Accepted'
                            "
                          >
                            {{ item.judgeInfo.message }}
                          </p>
                          <p
                            :style="{
                              color: '#f51d1d',
                            }"
                            v-if="
                              item.state === 1 &&
                              item.judgeInfo.message !== 'Accepted'
                            "
                          >
                            {{ item.judgeInfo.message }}
                          </p>
                          <p
                            :style="{
                              color: '#f51d1d',
                            }"
                            v-if="item.state === 2"
                          >
                            {{ item.judgeInfo.message }}
                          </p>
                          <p
                            :style="{
                              color: '#f51d1d',
                            }"
                            v-if="item.state === 3"
                          >
                            {{ item.judgeInfo.message }}
                          </p>
                        </template>
                        <a-row>
                          <a-col span="8">
                            执行用时 {{ item.judgeInfo?.time || "N/A" }}
                          </a-col>
                          <!--                          <a-col span="8">-->
                          <!--                            消耗内存 {{ item.judgeInfo?.memory || "N/A" }}-->
                          <!--                          </a-col>-->
                        </a-row>
                      </a-card>
                    </a-list-item>
                  </template>
                </a-list>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>

      <a-col class="col" span="16">
        <div id="parent">
          <a-select
            v-model="language"
            :style="{ width: '320px' }"
            placeholder="Please select ..."
          >
            <a-option>java</a-option>
            <a-option>python</a-option>
          </a-select>
          <CodeEditor
            :value="code"
            :language="language"
            :handle-change="handleChange"
          />
          <a-button
            type="primary"
            :style="{
              float: 'right',
            }"
            @click="handleSubmit"
            >提交
          </a-button>
        </div>
      </a-col>
    </a-row>
  </div>
  <a-drawer
    popup-container="#parent"
    :visible="judgeOk"
    :placement="'bottom'"
    :unmount-on-close="true"
    :render-to-body="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title> 提交结果</template>
    {{ judgeResult?.judgeInfo?.message }}
    <div v-if="judgeResult?.extra">
      <p>附加信息</p>
      <p style="white-space: pre-line">
        {{ judgeResult?.extra }}
      </p>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
import CodeEditor from "@/components/CodeEditor.vue";
import { onMounted, ref } from "vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSubmitControllerService,
  QuestionSubmitTinyQueryRequest,
  QuestionSubmitTinyVo,
  QuestionVo,
} from "@/service";
import { Message } from "@arco-design/web-vue";
import { useRoute } from "vue-router";
import ADDRESS from "@/config/address";
import SSEURL from "@/config/sseConfig";
import { QuestionResultVo } from "@/service/models/QuestionResultVo";

const route = useRoute();
const question = ref<QuestionVo>();
const language = ref<string>("java");
const code = ref<string>("");
const judgeData = ref<QuestionSubmitTinyVo[]>([]);
const id = parseInt(route.params.id + "");
const pageRequest = ref<QuestionSubmitTinyQueryRequest>({
  page: 1,
  pageSize: 5,
  id: id,
});
const judgeOk = ref<boolean>(false);
const judgeResult = ref<QuestionResultVo>({});
const handleChange = (s: string) => {
  code.value = s;
};
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionById(id);
  if (res.code != 0) {
    Message.error("数据加载失败：" + res.message);
    return;
  }
  question.value = res.data ?? {};
};
const loadJudgeData = async () => {
  const res =
    await QuestionSubmitControllerService.listMyQuestionSubmitTinyVoByPage(
      pageRequest.value
    );
  if (res.code != 0) {
    Message.error("提交记录加载失败：" + res.message);
    return;
  }
  judgeData.value = res.data?.records ?? [];
  paginationProps.value.total = res.data?.total ?? 0;
};
const onPageChange = (page: any) => {
  pageRequest.value.page = page;
  loadJudgeData();
};
const paginationProps = ref({
  defaultPageSize: 5,
  total: 0,
});
const createSseConnection = () => {
  const eventSource = new EventSource(ADDRESS + SSEURL, {
    withCredentials: true,
  });
  eventSource.onmessage = (event: MessageEvent) => {
    console.log(event);
    judgeOk.value = true;
    judgeResult.value = JSON.parse(event.data);
    console.log(judgeResult.value?.extra);
  };
};
//提交答案
const handleSubmit = async () => {
  //创建题目答案返回通知的SSE连接
  createSseConnection();
  const res = await QuestionSubmitControllerService.addQuestionSubmit({
    code: code.value,
    lang: language.value,
    questionId: id,
  });
  if (res.code != 0) {
    Message.error("题目提交失败：" + res.message);
    return;
  }
  Message.success("题目提交成功");
};
const handleOk = () => {
  judgeOk.value = false;
};
const handleCancel = () => {
  judgeOk.value = false;
};
onMounted(() => {
  loadData();
  loadJudgeData();
});
</script>

<style scoped>
#main {
  height: 100%;
}

#row {
  height: 100%;
}

.col {
  height: 100%;
}
</style>
